package com.ktwlsoft.archivemanage.config.exception;

import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 *
 * @author Name on 2023/7/21 9:54
 * @version 1.0
 */
@Log4j2
@RestControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(Throwable.class)
    public ResponseEntity<?> systemExceptionHandler(Throwable throwable, HttpServletRequest request) {
        log.error("URL:{} ,系统异常", request.getRequestURI(), throwable);
        return ResponseEntity.ok(Result.body(null, ResultType.BUSINESS_ERROR).withMessage(throwable.getMessage()));
    }
    @ExceptionHandler(BadCredentialsException.class)
    public ResponseEntity<?> systemExceptionHandler(BadCredentialsException e, HttpServletRequest request) {
        log.error("URL:{} ,系统异常", request.getRequestURI(), e);
        return ResponseEntity.ok(Result.body(null, ResultType.BUSINESS_ERROR).withMessage("密码错误"));
    }
    @ExceptionHandler(UsernameNotFoundException.class)
    public ResponseEntity<?> usernameNotFoundExceptionHandler(UsernameNotFoundException e, HttpServletRequest request) {
        log.error("URL:{} ,系统异常", request.getRequestURI(), e);
        return ResponseEntity.ok(Result.body(null, ResultType.BUSINESS_ERROR).withMessage(e.getMessage()));
    }





    @ExceptionHandler(value = ResultException.class)
    public ResponseEntity<?> resultExceptionHandler(ResultException e){
        return ResponseEntity.ok(e.getResult());
    }


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<?> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        return ResponseEntity.ok(Result.body(null, ResultType.CHECK_ERROR).withMessage(e.getBindingResult().getFieldError().getDefaultMessage()));
    }
}